package com.heima.wemedia.task;

import com.heima.common.delayTask.RedisDelayedQueueUtil;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.service.WmNewsAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DelayTask {


    @Autowired
    private RedisDelayedQueueUtil delayedQueueUtil;
    @Autowired
    private WmNewsAuditService auditService;


    @PostConstruct
    public void doTask(){

//        创建可以周期执行的线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
//        创建可以缓存的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

//        周期执行，每秒中从redis延迟队列中获取元素
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

//                从redis延迟队列中获取元素
                try {
                    Object obj = delayedQueueUtil.getDelayQueue("wm.news.pub");
                    if(obj == null){
                        return ;
                    }
                    Integer wmNewsId = Integer.valueOf(obj.toString());
                    log.info("延迟元素，wmNewsId={}",wmNewsId);
//                    实现业务解耦，发布文章
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
//                            发布文章
                            WmNewsResultDTO dto = new WmNewsResultDTO();
                            dto.setId(wmNewsId);
                            auditService.publishWmNews(dto);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },0,1, TimeUnit.SECONDS);

    }

}
